<?php
header('Content-Type: application/json');

// 获取前端发送的id数据
$id = isset($_GET['id']) ? $_GET['id'] : '';

// 连接数据库
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "fish";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

$delete_status = '';

// 如果有id值，执行删除操作
if ($id != '') {
    // 查询需要删除的记录
    $sql = "SELECT * FROM vuemodel WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    // 删除图片和glb模型文件
    $image_deleted = false;
    $glb_deleted = false;
    if ($row) {
        $image_path = $row['image'];
        $glb_path = $row['glb'];

        // Remove "https://ringstar.top/api/frond/" part from the paths
        $prefix = "https://ringstar.top/api/frond/";
        $image_path = str_replace($prefix, "./", $image_path);
        $glb_path = str_replace($prefix, "./", $glb_path);

        if (file_exists($image_path)) {
            $image_deleted = unlink($image_path);
        }
        if (file_exists($glb_path)) {
            $glb_deleted = unlink($glb_path);
        }
    }

    // 从数据库中删除记录，只有当图片和glb模型文件删除成功时
    if ($image_deleted && $glb_deleted) {
        $sql = "DELETE FROM vuemodel WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        $result = $stmt->execute();

        // 更新删除状态
        if ($result) {
            $delete_status = '删除成功';
        } else {
            $delete_status = '删除失败';
        }
    } else {
        $delete_status = '删除失败';
    }
}

// 关闭连接
$conn->close();

// 将结果以JSON格式返回
$response = array(
    'delete_status' => $delete_status,
    // 'image_path' => $image_path,
    // 'glb_path' => $glb_path
);
echo json_encode($response);
?>
